package cn.lili.common.test.sms;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ObjectCannedACL;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UploadObject {

    public static void main(String[] args) throws IOException {
        try {
            final String usage = "\n" +
                    "Usage:\n" +
                    "  <bucketName> <objectKey> <objectPath> \n\n" +
                    "Where:\n" +
                    "  bucketName - The Amazon S3 bucket to upload an object into.\n" +
                    "  objectKey - The object to upload (for example, book.pdf).\n" +
                    "  objectPath - The path where the file is located (for example, C:/AWS/book2.pdf). \n\n";

//            if (args.length != 3) {
//                System.out.println(usage);
//                System.exit(1);
//            }

            String bucketName = "little-amigos";
            String objectKey = "test"+System.currentTimeMillis() + ".png";
            String objectPath = "E:\\tmp\\视频\\封面.png";
            ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create();
            Region region = Region.AP_SOUTHEAST_2;
            S3Client s3 = S3Client.builder()
                    .region(region)
                    .credentialsProvider(credentialsProvider)
                    .build();

            putS3Object(s3, bucketName, objectKey, objectPath);
            s3.close();


        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }

    public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) {
        try {
            Map<String, String> metadata = new HashMap<>();
            metadata.put("x-amz-meta-myVal", "test");
            PutObjectRequest putOb = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .metadata(metadata)
                    .acl(ObjectCannedACL.PUBLIC_READ)
                    .build();
            s3.putObject(putOb, RequestBody.fromFile(new File(objectPath)));
            System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName);

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}

